#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import annotations

import logging
import os
from datetime import datetime


from typing import TYPE_CHECKING

from loguru import logger

from autoapi.core.path_conf import autoapi_path

if TYPE_CHECKING:
    import loguru


class PropagateHandler(logging.Handler):
    def emit(self, record) -> None:  # noqa: ANN001
        logging.getLogger(record.name).handle(record)


class Logger:
    @staticmethod
    def log() -> loguru.Logger:
        """
        日志记录器

        :return:
        """
        log_path = autoapi_path.log_dir

        if not os.path.join(log_path):
            os.makedirs(log_path)
        current_date = datetime.now().strftime("%Y-%m-%d")
        log_file = os.path.join(log_path, f"autoapi_{current_date}.log")

        # 清除 logger 配置
        logger.remove()

        # 将 logging message 替换为 loguru message
        logger.add(PropagateHandler(), format="<level>{message}</level>")

        # 输出到文件
        logger.add(
            log_file,
            format="[{time:YYYY-MM-DD HH:mm:ss}] [{file.name}:{line}] [{level}]: {message}",
            level="DEBUG",
            rotation="00:00",
            retention="7 days",
            encoding="utf8",
            enqueue=True,
            backtrace=True,
            diagnose=False,
            catch=True,
        )

        return logger


log = Logger().log()
